package de.baumann.browser.activitys

import android.app.Activity
import android.content.Intent
import android.net.Uri
import android.view.LayoutInflater
import android.view.MotionEvent
import android.view.View
import android.view.ViewGroup
import android.widget.RadioButton
import android.widget.RelativeLayout
import android.widget.TextView
import com.zhy.view.flowlayout.FlowLayout
import com.zhy.view.flowlayout.TagAdapter
import de.baumann.browser.R
import de.baumann.browser.activitys.user.BindPhoneActivity.Companion.startSettingPhoneActivity
import de.baumann.browser.adapter.CompleteAdapter
import de.baumann.browser.api.net.base.OdinUtil
import de.baumann.browser.api.net.vo.LoginInfo
import de.baumann.browser.api.net.vo.Version
import de.baumann.browser.base.BaseOdinActivity
import de.baumann.browser.base.BaseOdinFragment
import de.baumann.browser.db.Record
import de.baumann.browser.db.RecordAction
import de.baumann.browser.fragments.*
import de.baumann.browser.fragments.explore.ExploreFragments
import de.baumann.browser.iview.IinitView
import de.baumann.browser.present.AppConfigPresenter
import de.baumann.browser.present.InitPresenter
import de.baumann.browser.utils.*
import de.baumann.browser.utils.Constants.LOGINCODE
import de.baumann.browser.utils.web3j.WalletDaoUtils
import de.baumann.browser.views.dialog.BindPhoneDialog
import de.baumann.browser.views.dialog.MenuDialog
import de.baumann.browser.views.dialog.UpdateDialog
import de.baumann.browser.views.widget.SearchView
import kotlinx.android.synthetic.main.activity_main.*
import de.baumann.browser.fragments.MineFragments.Companion as MineFragments

class MainActivity : BaseOdinActivity<IinitView, InitPresenter>(), IinitView, MenuDialog.MenuClickListener {

    override fun getLayout(): Int {
        return R.layout.activity_main
    }

    private lateinit var action: RecordAction
    private var currentFragment: BaseOdinFragment<*, *>? = null
    private lateinit var currentChecked: RadioButton

    private lateinit var indexFragment: IndexFragment


    override fun initView() {
        indexFragment = IndexFragment.getInstance()
        supportFragmentManager.beginTransaction()
                .add(R.id.mainContainer, indexFragment)
                .commit()
        currentChecked = rbIndex
        currentFragment = indexFragment
        bottom_navgation.setOnCheckedChangeListener { _, checkedId ->
            when (checkedId) {
                R.id.rbIndex -> {
                    currentChecked = rbIndex
                    switchLayout(indexFragment)
                }
                R.id.rbMining -> {
//                    if (isLogined() && !isBindValidWalletAddress()) {
//                        showShortToast("请导入绑定的ODIN地址,所对应的钱包")
//                        currentChecked.isChecked = true
//                        return@setOnCheckedChangeListener
//                    }
                    currentChecked = rbMining
                    switchLayout(MiningFragment.getInstance())
                }
                R.id.rbExplore -> {
                    currentChecked = rbExplore
                    switchLayout(ExploreFragments.instance)
                }
                R.id.rbMine -> {
                    currentChecked = rbMine
                    switchLayout(MineFragments.instance)
                }

                R.id.rbMenu -> {
                    switchLayout(HomeWalletFragment.instance)
                    currentChecked = rbMenu
                }
            }
        }
    }

    private fun switchLayout(fragment: BaseOdinFragment<*, *>) {
        currentFragment = fragment
        supportFragmentManager.beginTransaction()
                .replace(R.id.mainContainer, fragment)
                .commitAllowingStateLoss()

    }

    override fun initData() {
        AppConfigPresenter().getActiveConfig()
        if (WalletDaoUtils.loadAll().size > 0) {
            if (getBoolean("isfirst")) {
            } else {
                saveMoneyAddress(WalletDaoUtils.loadAll()[0].address)
                put("isfirst", true)
            }

        }
        presenter.updateVersion()
//        if (getPhoneStatus() != 1) {
//            alertBindPhoneDialog()
//        } else {
//            getFreeLicence()
//        }

        action = RecordAction(this)
    }


    private fun isBindValidWalletAddress(): Boolean {
        val user = getUser()
        var ethAddress = user?.eth_address
        if (ethAddress != null) {
            if (ethAddress.startsWith("odx")) {
                ethAddress = "0${ethAddress.substring(2)}"
            }
            val ethWallet = WalletDaoUtils.queryWalletByAddress(ethAddress)
            return ethWallet != null
        }
        return false
    }

    override fun createPresenter(): InitPresenter {
        return InitPresenter()
    }

    override fun createView(): IinitView {
        return this
    }

    override fun onActivityResult(requestCode: Int, resultCode: Int, data: Intent?) {
        super.onActivityResult(requestCode, resultCode, data)
        if (requestCode == LOGINCODE && resultCode == Activity.RESULT_OK) {
            if (currentFragment != null) {
                currentFragment!!.initData()

            }
        }

    }

    override fun onNewIntent(intent: Intent?) {
        super.onNewIntent(intent)
        if (currentFragment != null) {
            currentFragment!!.onNewIntent()
        }
    }

    private lateinit var searchView: SearchView
    fun showSearchView() {
        searchView = SearchView(mContext)
        val w = ViewGroup.LayoutParams.MATCH_PARENT
        searchView.layoutParams = RelativeLayout.LayoutParams(w, w)
        mRootView.addView(searchView)
        searchView.bringToFront()
        updateAutoComplete()
        searchView.inputBox.dropDownWidth = ViewUtil.getWindowWidth(this)
        searchView.inputBox.setOnItemClickListener { _, view, _, _ ->
            val url = view.findViewById<TextView>(R.id.record_item_url).text.toString()
            WebSiteActivity.startWebSiteActivity(mContext, url)
            hideSoftInput(searchView.inputBox)
            hideSearchView()
        }
        searchView.inputBox.setOnEditorActionListener { _, _, _ ->
            val query = searchView.inputBox.text.trim().toString()
            if (query.isEmpty()) {
                showShortToast(getString(R.string.toast_input_empty))
                true
            }
            WebSiteActivity.startWebSiteActivity(mContext, query)
            hideSoftInput(searchView.inputBox)
            hideSearchView()
            action.open(false)
            if (!action.checkSearch(query)) {
                action.addSearch(Record(query, "", System.currentTimeMillis()))
            }
            false
        }

        action.open(false)
        val records = action.listSearch()
        searchView.tagFlowLayout.adapter = object : TagAdapter<Record>(records) {
            override fun getView(parent: FlowLayout, position: Int, record: Record): View {
                val tv = LayoutInflater.from(mContext).inflate(R.layout.layout_flow_item, searchView.tagFlowLayout, false) as TextView
                tv.text = record.title
                return tv
            }
        }
        searchView.tagFlowLayout.setOnTagClickListener { _, position, _ ->
            WebSiteActivity.startWebSiteActivity(mContext, records[position].title)
//            load(records[position].title)
            hideSearchView()
            true
        }
    }

    fun hideSearchView() {
        mRootView.removeView(searchView)
        mainContainer.bringToFront()
        bottom_navgation.bringToFront()
    }

    private fun updateAutoComplete() {
        action.open(false)
        val list = action.listBookmarks()
        list.addAll(action.listHistory())
        action.close()
        val adapter = CompleteAdapter(this, list)
        searchView.inputBox.setAdapter(adapter)
        adapter.notifyDataSetChanged()
    }

    /**
     * [LoginInfo.getPhoneStatus]  不为1 时
     * alert 绑定手机号的对话框
     */
    private var bindPhoneDialog: BindPhoneDialog? = null

    fun alertBindPhoneDialog() {
        bindPhoneDialog = BindPhoneDialog(mContext, View.OnClickListener {
            bindPhoneDialog!!.dismiss()
            startSettingPhoneActivity((mContext as Activity), "", 1033)
        })
        bindPhoneDialog!!.setOnCancelListener {
            presenter.getFreeLicence()
        }
        bindPhoneDialog!!.show()
    }


    private var mExitTime: Long = 0
    override fun onBackPressed() {
        if (indexFragment.isClosed) {
            indexFragment.openPager()
            return
        }

        if (System.currentTimeMillis() - mExitTime > 2000) {
            showShortToast(getString(R.string.press_again_to_exit_program))
            mExitTime = System.currentTimeMillis()
        } else {
            super.onBackPressed()
        }
    }

    override fun update(version: Version) {
        val versionCode = version.versionCode
        val localCode = OdinUtil.getAppVersionCode(mContext)
        if (versionCode <= localCode) {
            return
        }

        val updateDialog = UpdateDialog(mContext, View.OnClickListener {
            val intent = Intent()
            val newsurl = Uri.parse(version.updateUrl)
            intent.data = newsurl
            intent.action = "android.intent.action.VIEW"

            this.startActivity(intent)
//            val apkDownloadManager = AppDownloadManager(this@MainActivity)
//            apkDownloadManager.onResume()
//            apkDownloadManager.downloadApk(version.updateUrl, getString(R.string.app_name), getString(R.string.version_update))
        })
        updateDialog.setUpdateDesc(version.updateDesc)

        if (version.force == 1) {
            updateDialog.setCancelable(false)
        } else {
            updateDialog.setCancelable(true)
        }
        updateDialog.show()
    }

    override fun getFreeLicenceSuccess() {

    }

    override fun onClickDownload() {
    }

    override fun onClickAddBookmark() {
    }


    //登录
    override fun onClickLogin() {
//        if (!isLogined()) {
////            LoginActivity.startLoginActivity(this)
//        }
    }

    override fun onClickRefresh() {

    }

    //历史
    override fun onClickHisttory() {
        BookMarkAddHistoryActivity.startBookMarkAddHistoryActivity(mContext)
    }

    //设置
    override fun onClickSetting() {
        SettingActivity.startSettingActivity(mContext)
    }

    override fun onClickAbout() {
        H5Activity.startAboutOdinActivity(mContext, Constants.ABOUT_ODIN_URL)
    }

    override fun onClickFeedback() {
        if (getIsLogin()) {
            FeedBackActivity.startFeedBackActivity(mContext)
        } else {
//            showLoginDialog()
        }
    }

    //多窗口
    override fun onClickWindows() {
        WebSiteActivity.startWebSiteActivity(mContext, "")
    }

    var dispatchTouchListener: DispatchTouchListener? = null

    override fun dispatchTouchEvent(ev: MotionEvent?): Boolean {
        if (dispatchTouchListener != null) {
            dispatchTouchListener?.dispatchTouchEvent(ev)
        }
        return super.dispatchTouchEvent(ev)
    }

    interface DispatchTouchListener {
        fun dispatchTouchEvent(ev: MotionEvent?)
    }

}
